<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '满易开门',
  },
  needLogin: true,
  home: true,
}
</route>

<template>
  <view class="gate-devices-container p-4">
    <scroll-view
      scroll-y
      :show-scrollbar="false"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      refresher-background="#F8F8F8"
      class="h-full"
    >
      <view class="device-list">
        <view
          v-for="device in devices"
          :key="device.id"
          class="device-item bg-white rounded-lg p-4 mb-3"
        >
          <view class="flex justify-between items-center mb-2">
            <text class="text-lg font-medium">{{ device.name }}</text>
            <text :class="['status-tag', device.status ? 'status-online' : 'status-offline']">
              {{ device.status ? '在线' : '离线' }}
            </text>
          </view>

          <view class="text-gray-500 text-sm mb-4">
            <view>设备ID: {{ device.id }}</view>
          </view>

          <view class="flex justify-around space-x-3">
            <wd-button
              :disabled="!device.status"
              class="flex-1"
              type="primary"
              @click="handleOpenDoor(device)"
            >
              开门
            </wd-button>
<!--            <wd-button
              :disabled="!device.status"
              class="flex-1"
              type="error"
              @click="handleCloseDoor(device)"
            >
              关门
            </wd-button> -->
          </view>
        </view>
      </view>

      <!-- 暂无数据 -->
      <view v-if="devices.length === 0" class="flex flex-col items-center justify-center py-8">
        <image src="/static/empty.png" mode="aspectFit" class="w-32 h-32 mb-4" />
        <text class="text-gray-400">暂无设备数据</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store'
import type { components } from '@/types/ApiInterface'
import { closeDoorAPI, getUserGatePermissionAPI, openDoorAPI } from '@/service/iam'

const userStore = useUserStore()
const communityId = userStore.currentCommunity?.community.id
const devices = ref<
  {
    id: string
    location: string
    name: string
    status: boolean
  }[]
>([])
const getName = (item: components['schemas']['GatePermissionUserResponse']) => {
  if (item.deviceBuildingName) {
    return item.deviceName + '(楼栋门)'
  } else if (item.deviceUnitName) {
    return item.deviceName + '(单元门)'
  }
  return item.deviceName + '(小区大门)'
}

// 获取设备列表
const getDeviceList = async () => {
  try {
    const res = await getUserGatePermissionAPI(communityId)
    devices.value = res.data.map((item) => ({
      id: item.deviceId,
      location: getName(item),
      name: getName(item),
      status: item.status,
    }))
  } catch (error) {
    console.error('获取设备列表失败:', error)
    uni.showToast({
      title: '获取设备列表失败',
      icon: 'error',
    })
  }
}

// 开门操作
const handleOpenDoor = async (device: { id: string }) => {
  console.log('开门操作:', device)
  try {
    await openDoorAPI(device.id, communityId)
    uni.showToast({
      title: '开门成功',
      icon: 'success',
    })
  } catch (error) {
    uni.showToast({
      title: '开门失败',
      icon: 'error',
    })
  }
}

// 关门操作
const handleCloseDoor = async (device: { id: string }) => {
  console.log('关门操作:', device)
  try {
    await closeDoorAPI(device.id, communityId)
    uni.showToast({
      title: '关门成功',
      icon: 'success',
    })
  } catch (error) {
    uni.showToast({
      title: '关门失败',
      icon: 'error',
    })
  }
}

// 添加刷新状态
const isRefreshing = ref(false)

// 添加刷新方法
const onRefresh = async () => {
  isRefreshing.value = true
  try {
    await getDeviceList()
  } finally {
    isRefreshing.value = false
  }
}

onMounted(() => {
  const currentCommunity = userStore.currentCommunity
  const role = currentCommunity?.role
  if (role === 'ADMIN' || role === 'PMC_WORKER') {
  }
  getDeviceList()
})
</script>

<style lang="scss" scoped>
.gate-devices-container {
  box-sizing: border-box;
  height: calc(90vh - var(--status-bar-height));
  overflow: hidden;
  background-color: #f8f8f8;
}

.device-item {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.status-tag {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
}

.status-online {
  color: #52c41a;
  background-color: #e6f7e6;
}

.status-offline {
  color: #ff4d4f;
  background-color: #fff1f0;
}
</style>
